package util

import (
	"strconv"
	"strings"

	"mall/service/setting/rpc/settingclient"
)

const (
	arrayValueSeparator    = ","
	keyValueSeparator      = ":"
	keyOpSeparator         = ","
	arrayKeyValueSeparator = ";"
)

func ParseSorter(sorter *string) (res []*settingclient.OrderBy) {
	if sorter == nil {
		return
	}

	sorters := strings.Split(*sorter, arrayKeyValueSeparator)
	if len(sorters) == 0 {
		return
	}

	for _, orderBy := range sorters {
		orderBys := strings.Split(orderBy, keyValueSeparator)

		if len(orderBys) == 2 {
			res = append(res, &settingclient.OrderBy{
				Field: orderBys[0],
				Order: orderBys[1],
			})
			continue
		}

		if len(orderBys) == 1 {
			res = append(res, &settingclient.OrderBy{
				Field: orderBys[0],
				Order: "0",
			})
		}
	}

	return
}

func ParseSorterNew(sorter *string) (res []*settingclient.OrderBy) { // ##24.11.07## 完成
	if sorter == nil {
		return
	}

	sorters := strings.Split(*sorter, arrayKeyValueSeparator)
	if len(sorters) == 0 {
		return
	}

	for _, orderBy := range sorters {
		orderBys := strings.Split(orderBy, keyValueSeparator)

		if len(orderBys) == 2 && len(orderBys[0]) > 0 {
			ascOrDesc := "0"
			if len(orderBys[1]) > 0 {
				ascOrDesc = orderBys[1]
			}
			res = append(res, &settingclient.OrderBy{
				Field: orderBys[0],
				Order: ascOrDesc,
			})
			continue
		}

		if len(orderBys) == 1 && len(orderBys[0]) > 0 {
			res = append(res, &settingclient.OrderBy{
				Field: orderBys[0],
				Order: "0",
			})
		}
	}

	return
}

func ParseFilter(filter *string) (res []*settingclient.FilterBy) {
	if filter == nil {
		return
	}

	filters := strings.Split(*filter, arrayKeyValueSeparator)
	if len(filters) == 0 {
		return
	}

	for _, filterBy := range filters {
		filterBys := strings.Split(filterBy, keyValueSeparator)

		if len(filterBys) == 2 {
			res = append(res, &settingclient.FilterBy{
				Field: filterBys[0],
				In:    filterBys[1],
			})
		}
	}

	return
}

func ParseFilterNew(filter *string, postType *uint32) (res []*settingclient.FilterBy) { // ##24.11.07## 完成
	if filter != nil {
		filters := strings.Split(*filter, arrayKeyValueSeparator)
		if len(filters) > 0 {
			for _, filterBy := range filters {
				filterBys := strings.Split(filterBy, keyValueSeparator)

				if len(filterBys) == 2 && len(filterBys[0]) > 0 && len(filterBys[1]) > 0 {
					res = append(res, &settingclient.FilterBy{
						Field: filterBys[0],
						In:    filterBys[1],
					})
				}
			}
		}
	}

	if postType != nil {
		res = append(res, &settingclient.FilterBy{
			Field: "type",
			In:    strconv.FormatInt(int64(*postType), 10),
		})
	}

	return
}
